package cn.acheng.cams.trigger.http.interceptor;


import cn.acheng.cams.type.context.ThreadContext;
import cn.acheng.cams.type.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Value("${cams.jwt.config.secret-key}")
    private String secretKey;

    @Value("${cams.jwt.config.ttl}")
    private Integer ttl;

    @Value("${cams.jwt.config.token-name}")
    private String tokenName;

    private static final String USER_ID = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是不是请求静态资源
        if(!(handler instanceof HandlerMethod)){
            return true;
        }


        //校验请求当中携带令牌的格式以及令牌是否为空
        String token = request.getHeader(tokenName);
        if(token == null || token.isEmpty()){
            log.info("令牌为空");
            return false;
        }
        if(!token.startsWith("Bearer ")){
            log.info("令牌格式不正确：{}",token);
            return false;
        }

        token = token.substring(7);
        log.info("令牌校验:{}",token);
        //校验令牌是否被篡改
        try{
            Claims claims = JwtUtil.parseJWT(secretKey, token);
            Map<String,Object> map = new HashMap<>();
            map.put("username",claims.get("username"));
            map.put("role",claims.get("role"));
            log.info("此次请求用户名：{} 用户身份：{}",claims.get("username"),claims.get("role"));
            ThreadContext.setUserData(map);
        }catch (JwtException ex){
            if(ex instanceof ExpiredJwtException){
                log.warn("jwt令牌已过期");
            }else{
                log.warn("jwt令牌解析失败");
            }
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadContext.removeUserData(); // 清理 ThreadLocal
    }
}
